package com.jz.socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by Administrator on 2015/11/12.
 * 服务端心跳线程
 */
abstract public class HeartBeatServerThread extends Thread {
    public static final Logger LOGGER = LoggerFactory.getLogger(HeartBeatServerThread.class);
    private ServerSocket socketServer = null;
    private String HEARTBEAT_IP = "127.0.0.1";
    private int HEARTBEAT_PORT = 10101;

    public static void main(String[] args) {
        new HeartBeatServerThread() {
            @Override
            public void handle() {

            }

            @Override
            public void initError() {

            }
        };
    }

    public HeartBeatServerThread() {
        super();
        init();
        start();
    }

    public HeartBeatServerThread(String ip, int port) {
        super();
        this.HEARTBEAT_IP = ip;
        this.HEARTBEAT_PORT = port;
        init();
        start();
    }

    private void init() {
        try {
            LOGGER.info("start heart-beat server thread");
            socketServer = new ServerSocket(HEARTBEAT_PORT, 1024, InetAddress.getByName(HEARTBEAT_IP));
        } catch (Exception e) {
            LOGGER.error("服务端-心跳线程初始化失败", e);
            initError();
        }
    }

    public void run() {
        try {
            while (true) {
                Socket socket = socketServer.accept();
                InputStream in = socket.getInputStream();
                byte[] b = new byte[7];
                int len;
                try {
                    while ((len = in.read(b)) != -1) {
//                        String value = new String(b, 0, len);
                    }
                } catch (Exception e) {
                    LOGGER.error("服务端与客户端心跳连接断开", e);
                    handle();
                }
            }
        } catch (Exception e) {
            LOGGER.error("服务端与客户端心跳连接断开", e);
            handle();
        }
    }

    public void close() {
        try {
            if (socketServer != null) {
                socketServer.close();
            }
        } catch (IOException e) {
            LOGGER.error("", e);
        }
    }

    abstract public void handle();

    abstract public void initError();
}